<template>
    <div class="content">
      <div class="content-head">
        <el-form :inline="true" :model="formData" label-position="left">
          <el-form-item label="选择日期" label-width="70px" class="form-item">
            <el-date-picker v-model="formData.startAndEndDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" size="mini" :clearable="false" style="width:220px;"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-refresh-left" @click="reset_btn">重置</el-button>
            <el-button type="success" size="mini" icon="el-icon-search" @click="search_btn">查询</el-button>
            <el-button type="info" size="mini" icon="el-icon-download" :loading="exportBtnLoading" @click="export_btn">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="content-table">
        <div class="table-info">
          <div class="info-left">
            <el-radio-group v-model="showType" @input="showTypeChange" size="mini">
              <el-radio-button label="日报"></el-radio-button>
              <el-radio-button label="周报"></el-radio-button>
              <el-radio-button label="月报"></el-radio-button>
            </el-radio-group>
          </div>
          <div class="info-right">生产{{ showType }}</div>
        </div>
        <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" :max-height="tableMaxHeight" border class="content-table-item">
          <el-table-column prop="workShop" label="部门" width="" align="center"></el-table-column>
          <el-table-column prop="productCode" label="产品" width="" align="center">
            <template slot-scope="scope" slot="header">
              <table-head-filter label="产品" type="input" :bindData="formData.productCode" filterField="productCode" @change="filterChangeEvent"></table-head-filter>
            </template>
          </el-table-column>
          <el-table-column prop="workReportType" label="工序" width="" align="center"></el-table-column>
          <el-table-column prop="deviceNum" label="设备数" width="" align="center"></el-table-column>
          <el-table-column prop="beat" label="节拍" width="" align="center"></el-table-column>
          <el-table-column prop="runTime" label="运行工时" width="" align="center"></el-table-column>
          <el-table-column prop="targetCapacity" label="目标产能" width="" align="center"></el-table-column>
          <el-table-column prop="actualCapacity" label="实际产能" width="" align="center"></el-table-column>
          <el-table-column prop="targetOee" label="目标OEE" width="" align="center"></el-table-column>
          <el-table-column prop="actualOee" label="实际OEE" width="" align="center"></el-table-column>
        </el-table>
      </div>
      <div class="content-footer">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,50,100,200]" :page-size="pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="total"></el-pagination>
      </div>
    </div>
  </template>
  
  <script>
  import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
  import TableHeadFilter from "@/components/tableHeadFilter/index.vue";
  import { reqProductionDailyReport,reqProductionDailyReportExport } from "@/api/workOrder.js";
  import T from "@/utils/tools.js";
  export default {
    name:"productionDailyReport",  //生产日报
    components:{
      TableHeadFilter
    },
    data() {
      return {
        formData:{
          startAndEndDate:[this.formatDate(null,1),this.formatDate(null,1)],
          productCode:''
        },
        tableData:[],
        tableLoading:false,
        tableMaxHeight:450,
        currentPage:1,
        pageSize:20,
        total:0,
        exportBtnLoading:false,
        showType:"日报",
      }
    },
    mounted(){
      this.getProductionDailyReport();
      //精致环境下进行自动旋转
      //autoOrientation();
      this.calculateTableMaxHeight();
      document.title = "生产日报";
      window.addEventListener("resize",this.calculateTableMaxHeight);
    },
    beforeDestroy(){
      window.removeEventListener("resize",this.calculateTableMaxHeight);
    },
    methods:{
      getProductionDailyReport(){
        const { startAndEndDate,productCode } = this.formData;
        const parameter = { page:this.currentPage,size:this.pageSize,startDate:startAndEndDate[0],endDate:startAndEndDate[1],productCode };
        this.tableLoading = true;
        reqProductionDailyReport(parameter).then(response => {
          if(response.data.code === 200){
            this.tableData = response.data.data.content;
            this.total = response.data.data.totalElements;
          }
          this.tableLoading = false;
          console.log('获取生产日报表api',response);
        }).catch(error => {
          this.tableLoading = false;
          this.$message.error("生产日报列表数据获取失败");
          console.log('获取生产日报表api',error);
        })
      },
      reset_btn(){
        this.formData.startAndEndDate = [this.formatDate(null,1),this.formatDate(null,1)];
        this.showType = "日报";
        this.getProductionDailyReport();
      },
      search_btn(){
        const { startAndEndDate } = this.formData;
        if(startAndEndDate.length !== 2){
          this.$message({type:"warning",message:"选择起始日期后进行查询"});
          return;
        }
        this.getProductionDailyReport();
      },
      export_btn() {
        const { startAndEndDate } = this.formData;
        const parameters = { startDate:startAndEndDate[0],endDate:startAndEndDate[1] };
        this.$confirm('即将导出当前内容,数据将根据筛选条件进行过滤', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
          .then(async () => {
              this.exportBtnLoading = true;
              let res = await reqProductionDailyReportExport(parameters);
              if (res.status === 200) {
                let blob = res.data;
                let url = window.URL.createObjectURL(blob,{type: 'application/zip'});
                const aLink = document.createElement('a');
                aLink.href = url;
                let timestamp = new Date().getTime();
                aLink.setAttribute('download', '生产日报_' + timestamp);
                document.body.appendChild(aLink);
                aLink.click();
                document.body.removeChild(aLink);
                this.$message.success('导出成功');
                this.exportBtnLoading = false;
              } else {
                const errMsg = res.data?.message || "导出失败,请重试";
                this.$message.error(errMsg);
                this.exportBtnLoading = false;
              }
          }).catch(() => {
            this.exportBtnLoading = false;
            this.$message({type: 'info', message: '已取消导出!'});       
          });
      },
      //分页器
      handleCurrentChange(curPage){
        this.currentPage = curPage;
        this.getProductionDailyReport();
      },
      handleSizeChange(pageSize){
        this.pageSize = pageSize;
        this.getProductionDailyReport();
      },
      showTypeChange(type){
        let start = T.dayjs().startOf('day').format('YYYY-MM-DD');
        let end = T.dayjs().endOf('day').format('YYYY-MM-DD');
        switch (type) {
          case '日报':
            start = T.dayjs().startOf('day').format('YYYY-MM-DD');
            end = T.dayjs().endOf('day').format('YYYY-MM-DD');
            break;
          case '周报':
            start = T.dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD');
            end = T.dayjs().endOf('week').add(1, 'day').format('YYYY-MM-DD');
            break;
          case '月报':
            start = T.dayjs().startOf('month').format('YYYY-MM-DD');
            end = T.dayjs().endOf('month').format('YYYY-MM-DD');
            break;
          default:
            break;
        }
        this.formData.startAndEndDate = [start,end];
        this.search_btn();
      },
      //格式化时间
      formatDate(val,type){
        let date = null;
        val === null ? date = new Date() : date = new Date(val);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let h = date.getHours();
        let m = date.getMinutes();
        let s = date.getSeconds();
        if(type === 0){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 1){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day);
        } else if (type === 2){
            return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 3){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
        }
      },
      addZero(val){
          return val > 9 ? val : "0" + val;
      },
      calculateTableMaxHeight(){
        const dom = document.querySelector(".content-table");
        this.$nextTick(() => {
          this.tableMaxHeight = dom.offsetHeight - 30;
        })
      },
      //tableHeadFiler的change事件
      filterChangeEvent(parameter){
        const { state, filterField, selectedValue } = parameter;
        if(state === 'clear'){
          //清空操作
          if(this.formData[filterField] !== ""){
            this.formData[filterField] = "";
            this.getProductionDailyReport();
          }
        }
        if(state === 'confirm'){
          //确定操作
          this.formData[filterField] = selectedValue;
          if(selectedValue !== ""){
            this.getProductionDailyReport();
          }
        }
      }
    }
  }
  </script>
  
  <style lang='scss' scoped>
  .content{
    width: 100%;
    height: 100%;
    padding: 5px;
    box-sizing: border-box;
  
    .content-head{
      width:100%;
      height:50px;
    }
    .content-table{
      width:100%;
      height:calc(100% - 50px - 50px);
      .table-info{
        width:100%;
        height: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 16px;
        color:#9195a3;
      }
    }
    .content-footer{
      width:100%;
      height:50px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
  </style>